package com.ak.httpclient;

import com.ak.utils.HttpUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


//@Slf4j
public class MyHttpPostParams {

    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(HttpUtils.cm).build();
        CloseableHttpResponse response=null;
        // 设置参数
        // 分析这个
        // https://www.baidu.com/s
        try {
            // 封装表单对象
            List<NameValuePair> params=new ArrayList<>();
            params.add(new BasicNameValuePair("keys","java"));

            // 输入网址
            HttpPost httpPost=new HttpPost("http://yun.itheima.com/search");
            UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(params,"utf-8");
            int agentNum = new Random().nextInt(HttpUtils.agents.size());
            // 设置配置
            httpPost.setConfig(HttpUtils.getConfig());
            // 设置表单内容
            httpPost.setEntity(formEntity);
            // 设置代理
            httpPost.addHeader("User-Agent", HttpUtils.agents.get(agentNum));

            // 获取响应内容
            response= httpClient.execute(httpPost);
            System.out.println(response);
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity());
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭流
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
